<!--
督办工单/廉小牛
 * @Author: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @Date: 2025-05-25 16:46:30
 * @LastEditors: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @LastEditTime: 2025-06-03 12:21:27
 * @FilePath: \nsk-ui\src\views\disciplinary\workOrder\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koroFileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="work">
    <div class="work-top">
      <div
        v-for="(value, key) in statsData"
        :key="key"
        class="work-top-item"
        :class="{
          pending: key === '待处理',
          feedback: key === '已阅',
          total: key === '年累计',
        }"
      >
        <div class="title">{{ key }}工单</div>
        <div class="num">{{ value }}个工单</div>
      </div>
    </div>
    <div class="work-table">
      <el-form
        :model="searchForm"
        class="search-form"
        inline
        style="margin-bottom: 12px"
      >
        <el-form-item label="工单编号">
          <el-input
            v-model="searchForm.workOrderNumber"
            placeholder="请输入工单编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="工单来源">
          <el-select
            v-model="searchForm.source"
            placeholder="请选择工单来源"
            clearable
          >
            <el-option label="12345" value="12345" />
            <el-option label="公众号" value="公众号" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理类型">
          <el-select v-model="searchForm.mark" placeholder="处理类型" clearable>
            <el-option label="未处理" value="未处理" />
            <el-option label="督办-未回复" value="督办-未回复" />
            <el-option label="督办-已回复" value="督办-已回复" />
            <el-option label="已阅" value="已阅" />
          </el-select>
        </el-form-item>
        <el-form-item label="督办日期">
          <el-date-picker
            v-model="searchForm.replyTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            placeholder="请选择督办日期区间"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item style="margin-right: 0">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" style="width: 100%" stripe>
        <el-table-column prop="source" label="工单来源" show-overflow-tooltip />
        <el-table-column
          prop="workOrderNumber"
          label="工单编号"
          show-overflow-tooltip
        />
        <el-table-column prop="mark" label="处理类型" show-overflow-tooltip>
          <template #default="{ row }">
            <span
              :style="{
                color: row.mark === '督办-未回复' ? '#ff4d4f' : 'inherit',
              }"
            >
              {{ row.mark }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="complaintCategoryLevel1"
          label="诉求分类（一级）"
          show-overflow-tooltip
        />
        <el-table-column
          prop="workOrderSubject"
          label="工单主题"
          show-overflow-tooltip
        />
        <el-table-column
          prop="workOrderContent"
          label="工单内容"
          show-overflow-tooltip
        />
        <el-table-column
          prop="superviseTime"
          label="督办日期"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="text" @click="handleOptions(row, 'view')">
              详情
            </el-button>

            <el-button
              v-if="row.mark === '督办-已回复' || row.mark === '督办-未回复'"
              type="text"
              @click="onReplyDrawerClick(row, 'view')"
              >查看回复</el-button
            >
            <!-- v-if="
                row.mark === '未处理' &&
                !(userStore.roles && userStore.roles.includes('jd'))
              " -->
            <el-button
              text
              type="warning"
              v-if="
                row.mark === '未处理' &&
                !(userStore.roles && userStore.roles.includes('jd'))
              "
              @click="handleOpenAssetDrawer(row)"
              >督办</el-button
            >
            <el-button
              v-if="
                row.mark === '未处理' &&
                !(userStore.roles && userStore.roles.includes('jd'))
              "
              type="text"
              @click="handleOptions(row, 'read')"
              >已阅</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <span class="total-count">总共 {{ total }} 个项目</span>
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next, jumper, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 详情 -->
    <detail-drawer
      v-if="drawerVisible"
      v-model:visible="drawerVisible"
      :type="drawerType"
      :asset-data="currentAssetData"
      page-type="督办工单"
    />

    <!-- 抽屉组件 -->
    <reply-drawer
      v-model:visible="replyDrawerVisible"
      :mode="replyDrawerMode"
      :work-order-data="currentAssetData"
      :reply-list="replyList"
      @submit="handleReplySubmit"
      @cancel="handleReplyCancel"
    />

    <asset-drawer
      v-if="assetVisible"
      v-model:visible="assetVisible"
      :type="drawerType"
      :asset-data="currentAssetData"
    />
  </div>
</template>

<script setup>
import ReplyDrawer from "@/components/ReplyDrawer.vue";
import { onMounted, reactive, defineAsyncComponent } from "vue";
import { getList, getInfo, isRead } from "@/api/workOrder.js";
import { ElMessage } from "element-plus";
import { getWorkOrderStats, getReplyList } from "./services";
import dayjs from "dayjs";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();

const replyDrawerMode = ref("reply");
const replyDrawerVisible = ref(false);
const replyList = ref([]);

const DetailDrawer = defineAsyncComponent(() =>
  import("@/components/DetailDrawer.vue")
);

const AssetDrawer = defineAsyncComponent(() =>
  import("./components/AssetDrawer.vue")
);
// 表格数据
const tableData = ref([]);
const total = ref(0);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
// 抽屉控制
const drawerVisible = ref(false);
const drawerType = ref("");
const currentAssetData = ref(null);
const assetVisible = ref(false);

const searchForm = reactive({
  workOrderNumber: "", // 工单编号
  source: "", // 工单来源
  mark: "", // 处理类型
  replyTimeRange: [], // 督办日期区间
});

// 修改统计数据
const statsData = ref({
  年累计: 0,
  待处理: 0,
  已阅: 0,
});

const handleOpenAssetDrawer = (row) => {
  assetVisible.value = true;
  drawerType.value = "supervise";
  currentAssetData.value = row;
};

const handleOptions = async (row, type) => {
  if (type === "read") {
    const res = await isRead({
      workOrdersId: row.id,
    });
    if (res.code !== 200) {
      ElMessage.error("已阅失败");
      return;
    }
    ElMessage.success("已阅成功");
    return;
  }

  const res = await getInfo(row.id);
  if (res.code !== 200) {
    this.$message.error("获取工单详情失败");
    return;
  }
  drawerVisible.value = true;
  drawerType.value = type;
  currentAssetData.value = res.data || {};
};
// 获取表格数据
const fetchTableData = async () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    isIdc: 0,
    ...searchForm,
  };
  if (params.replyTimeRange && params.replyTimeRange.length === 2) {
    params.params = {
      beginTime: dayjs(params.replyTimeRange[0]).format("YYYY-MM-DD 00:00:00"),
      endTime: dayjs(params.replyTimeRange[1]).format("YYYY-MM-DD 23:59:59"),
    };
    delete params.replyTimeRange;
  }
  const res = await getList(params);
  if (res.code === 200) {
    tableData.value = res.rows || [];
    total.value = res.total || 0;
  } else {
    ElMessage.error(res.msg || "获取列表数据失败");
  }
};
const handleSearch = () => {
  currentPage.value = 1;
  fetchTableData();
};
// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchTableData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTableData();
};

const onReplyDrawerClick = async (row, mode) => {
  currentAssetData.value = row;
  replyDrawerVisible.value = true;
  replyDrawerMode.value = mode;
  if (mode === "view") {
    // 获取工单回复列表
    const departmentId = userStore.dept.deptId;
    const orderId = row.id || row.orderId;
    const res = await getReplyList({ orderId, departmentId });
    if (res.code === 200) {
      replyList.value = res.rows || res.data || [];
    } else {
      replyList.value = [];
    }
  }
};

const handleReplySubmit = async (replyContent) => {
  const orderId = currentAssetData.value?.id;
  try {
    await postReply({ orderId, replyContent });
    ElMessage.success("回复成功");
    fetchTableData();
  } catch (e) {
    ElMessage.error("回复失败");
  }
};

const handleReplyCancel = () => {
  replyDrawerVisible.value = false;
};

// 修改获取统计数据的方法
const fetchStatsData = async () => {
  try {
    const res = await getWorkOrderStats();
    if (res.code === 200) {
      statsData.value = res.data || {
        年累计: 0,
        待处理: 0,
        已阅: 0,
      };
    } else {
      ElMessage.error(res.msg || "获取统计数据失败");
    }
  } catch (error) {
    console.error("获取统计数据失败：", error);
    ElMessage.error("获取统计数据失败，请稍后重试");
  }
};

onMounted(() => {
  fetchStatsData();
  fetchTableData();
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
.work-top-item {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.04);
  padding: 32px 0 24px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-width: 260px;
  min-height: 120px;
}
.work-top-item .title {
  color: #999;
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 12px;
  letter-spacing: 2px;
}
.work-top-item .num {
  font-size: 38px;
  font-weight: bold;
  line-height: 1.1;
  letter-spacing: 2px;
}
.work-top-item.total .num {
  color: #36b368;
}
.work-top-item.pending .num {
  color: #ff9900;
}
.work-top-item.feedback .num {
  color: #409eff;
}
.search-form {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 12px;
}
.search-form .el-form-item {
  margin-bottom: 0;
}
</style>
